package services

import (
	"errors"
	"hft/Database/admin"
	"hft/global"
	"hft/tools"

	"gorm.io/gorm"
)

type Route struct{}

func (r *Route) AddRoute(routes *admin.Route) error {

	err := global.OC_DB.Transaction(func(tx *gorm.DB) error {
		// 如果pid为0或者负数则改为1

		if routes.PID == 0 {
			routes.PID = 1
		}

		if res := tx.Model(&admin.Route{}).Where("name = ?", routes.Name).Omit("id").FirstOrCreate(&routes); res.Error != nil {
			return errors.New("未知错误")
		} else if res.RowsAffected == 0 {
			return errors.New("已存在该路由")
		} else {
			var SuperRole *admin.Role
			// 同时也给超级管理员添加
			tx.Where("id = ?", 1).First(&SuperRole)
			tx.Model(&SuperRole).Association("Routes").Append(routes)
			return nil
		}

	})

	return err
}

func (r *Route) EditRoute(routes *admin.Route) error {

	err := global.OC_DB.Transaction(func(tx *gorm.DB) error {

		if err := tx.Model(&admin.Route{}).Where("id = ?", routes.ID).Omit("id,p_id,create_time,delete_at").Save(&routes).Error; err != nil {

			return errors.New("无该路由存在")
		} else {

			var meta = routes.Meta

			tx.Model(&admin.Meta{}).Where("route_id = ?", routes.ID).Omit("id,create_time,delete_at,route_id").Save(&meta)

			return nil
		}
	})

	return err
}

func (r *Route) DeleteRoutes(ids []int) error {

	global.OC_DB.Unscoped().Delete(&admin.Route{}, ids)

	return nil
}

func (r *Route) GetRoutes(claims tools.BaseClaims) (routes []*admin.Route, err error) {

	var role *admin.Role
	var account *admin.Account
	var SearchRoutes = make([]*admin.Route, 0)

	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {

		// 找出对应的角色值
		if err := tx.Where("username = ? ", claims.Username).First(&account).Error; err != nil {
			return errors.New("无该用户信息")
		} else {
			if err := tx.Where("id = ?", account.RoleId).First(&role).Error; err != nil {
				return errors.New("无该角色信息")
			} else {
				tx.Model(&admin.Role{}).Preload("Routes", func(db *gorm.DB) *gorm.DB {
					return db.Order("sort asc").Preload("Meta").Preload("Apis", func(db *gorm.DB) *gorm.DB {
						return db.Select("*").Joins("left join `hft_roles_apis` on `hft_apis`.`id` = `hft_roles_apis`.`api_id`").Where("`role_id` = ?", account.RoleId)
					})
				}).First(&role)

				SearchRoutes = role.Routes

				return nil
			}
		}
	})

	if err != nil {
		return nil, err
	} else {
		return SearchRoutes, nil
	}
}

var RouteService = new(Route)
